//
//  AppDelegate.m
//  TNS
//
//  Created by parkin on 16/1/18.
//  Copyright © 2016年 zhongyan. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "MobClick.h"
#import "LoginViewController.h"
#import "Config.h"
#import "HomeViewController.h"
#import "WebViewController.h"
#import "PrivacyViewController.h"
#import "AboutUsViewController.h"
@interface AppDelegate ()


@end

@implementation AppDelegate
+ (AppDelegate *)shareInstance {
    return [[UIApplication sharedApplication] delegate];
}
- (void)reachabilityChanged:(NSNotification *)note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if (status == NotReachable) {
        [Config showMessage:@"您当前网络不给力,请稍后再试!"];
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNS
    [self registerUserNotification];
    // 处理远程通知启动 APP

    [self receiveNotificationByLaunchingOptions:launchOptions];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    LoginViewController *VC = [[LoginViewController alloc] init];
    self.navController = [[UINavigationController alloc] initWithRootViewController:VC];
    UITabBarController *bar = [[UITabBarController alloc] init];
    
    bar.delegate = self;
    bar.tabBar.backgroundImage = [UIImage imageNamed:@"foot_black"];
    self.navController.tabBarItem = [[UITabBarItem alloc] init];
    self.navController.tabBarItem.image = [[UIImage imageNamed:@"home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navController.tabBarItem.selectedImage = [[UIImage imageNamed:@"home_act"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navController.tabBarItem setImageInsets:UIEdgeInsetsMake(5, 0, -5, 0)];
    WebViewController *web = [[WebViewController alloc] init];
    self.navController1 = [[UINavigationController alloc] initWithRootViewController:web];
    self.navController1.tabBarItem.image = [[UIImage imageNamed:@"use"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navController1.tabBarItem.selectedImage = [[UIImage imageNamed:@"use_act"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navController1.tabBarItem setImageInsets:UIEdgeInsetsMake(5, 0, -5, 0)];
    PrivacyViewController *pri = [[PrivacyViewController alloc] init];
    self.navController2 = [[UINavigationController alloc] initWithRootViewController:pri];
    self.navController2.tabBarItem.image = [[UIImage imageNamed:@"privacy"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navController2.tabBarItem.selectedImage = [[UIImage imageNamed:@"privacy_act"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navController2.tabBarItem setImageInsets:UIEdgeInsetsMake(5, 0, -5, 0)];
    AboutUsViewController *about = [[AboutUsViewController alloc] init];
    self.navController3 = [[UINavigationController alloc] initWithRootViewController:about];
    self.navController3.tabBarItem.image = [[UIImage imageNamed:@"contact"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navController3.tabBarItem.selectedImage = [[UIImage imageNamed:@"contact_act"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navController3.tabBarItem setImageInsets:UIEdgeInsetsMake(7, 0, -7, 0)];
    bar.viewControllers = @[self.navController,self.navController1,self.navController2,self.navController3];
    self.window.rootViewController = bar;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    UIApplication *app = [UIApplication sharedApplication];
    app.applicationIconBadgeNumber = 0;
    // 监测网络情况
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name: kReachabilityChangedNotification
                                               object: nil];
    self.hostReach = [Reachability reachabilityWithHostName:@"www.google.com"];
    [self.hostReach startNotifier];
    
    [MobClick startWithAppkey:@"569cc7dee0f55ad92500246f" reportPolicy:BATCH channelId:@""];
    
    
    // Override point for customization after application launch.
    return YES;
}
#pragma mark - 用户通知(推送) _自定义方法
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    UIApplication *app = [UIApplication sharedApplication];
    app.applicationIconBadgeNumber = 1;

}
/** 注册用户通知 */
- (void)registerUserNotification {
    
    /*
     注册通知(推送)
     申请App需要接受来自服务商提供推送消息
     */
    
    // 判读系统版本是否是“iOS 8.0”以上
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ||
        [UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
        
        // 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        
        // 定义用户通知设置
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        
        // 注册用户通知 - 根据用户通知设置
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else { // iOS8.0 以前远程推送设置方式
        // 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        
        // 注册远程通知 -根据远程通知类型
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
}

/** 自定义：APP被“推送”启动时处理推送消息处理（APP 未启动--》启动）*/
- (void)receiveNotificationByLaunchingOptions:(NSDictionary *)launchOptions {
    if (!launchOptions)
        return;
    
    /*
     通过“远程推送”启动APP
     UIApplicationLaunchOptionsRemoteNotificationKey 远程推送Key
     */
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        NSLog(@"\n>>>[Launching RemoteNotification]:%@", userInfo);
    }
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *myToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    myToken = [myToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    [GeTuiSdk registerDeviceToken:myToken]; /// 向个推服务器注册 deviceToken
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n",myToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [GeTuiSdk registerDeviceToken:@""]; /// 如果 APNS 注册失败,通 知个推服务器
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n",error.description);
}
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢复 SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推 SDK 已注册,返回 clientId
    [[NSUserDefaults standardUserDefaults] setObject:clientId forKey:@"clientId"];
    while (![[NSUserDefaults standardUserDefaults] synchronize])
    {
    }
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告,集成步骤发生的任何错误都在这里通知,如果 集成后,无法正常收到消息,查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    UIApplication *app = [UIApplication sharedApplication];
    app.applicationIconBadgeNumber = 0;
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    UIApplication *app = [UIApplication sharedApplication];
    app.applicationIconBadgeNumber = 0;
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
